package com.placement.refresh.interceptor;

import java.lang.reflect.Method;
import java.util.Date;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

/**
 * @author Amit Chadha
 *
 */
public class RefreshLogInterceptor implements MethodInterceptor,
MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice{
	private static final Log logger = LogFactory.getLog(RefreshLogInterceptor.class);
	private static long startTime = System.currentTimeMillis();
//	private LolaContextService lolaContextService;
//	private LolaBatchService lolaBatchService;
	
	public RefreshLogInterceptor(){
		logger.debug("constructor LolaLogInterceptor..");
	}
	  public Object invoke(MethodInvocation methodInvocation) throws Throwable
	  {
		  logger.debug("LolaLogInterceptor invoke method");
	    //logger.info("BEGIN: " + methodInvocation.getMethod().getDeclaringClass() + "::" + methodInvocation.getMethod().getName());
	    
	    long startTime = System.currentTimeMillis();
	    try
	    {
	      Object retVal = methodInvocation.proceed();
	      return retVal;
	    }catch(Exception e){
	    	throw e;
	    }
	    finally
	    {
	      logger.info("TIME TAKEN: "  + methodInvocation.getMethod().getDeclaringClass() + "::" + methodInvocation.getMethod().getName()+"^"+(System.currentTimeMillis() - startTime)+" ms.");
	    }
	  }
	  
	  public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {			
		  if(arg0!=null && arg0.getName().equals("startBatch"))
		  {
/*			  int processId=LolaUtil.getProcessIdByClassName(arg2.getClass().getName());
			  String processName=LolaUtil.getProcessNameByClassName(arg2.getClass().getName());
			  logger.info("processId>>"+processId+">>processName"+processName);
			  if(processId!=-1 && processName !=null){
				  this.sendEmail("Started STEP:"+processId+" ("+processName+")", "STEP:"+processId+" ("+processName+") is started",LolaProperites.getProperty(Constants.LOLA_EMAIL_ADDRESSES));
				  if(processId==1){
					  this.sendStartBatchNotification();
				  }
			  }
*/			  
				  
		  }
		  //logger.info("BEGIN: "+arg0.getDeclaringClass()+" "+arg0.getName()+" "+System.currentTimeMillis());
		  startTime = System.currentTimeMillis();
		}
		
		public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {		
			
			if(arg1!=null && arg1.getName().equals("startBatch"))
			{
/*				int processId=LolaUtil.getProcessIdByClassName(arg3.getClass().getName());
				String processName=LolaUtil.getProcessNameByClassName(arg3.getClass().getName());
				logger.info("processId>>"+processId+">>processName"+processName);
				if(processId!=-1 && processName !=null){
					this.sendEmail("Completed STEP:"+processId+" ("+processName+")", "STEP:"+processId+" ("+processName+") is Completed. Process took "+(System.currentTimeMillis() - startTime)+" ms",
							LolaProperites.getProperty(Constants.LOLA_EMAIL_ADDRESSES));
					if(processId==Constants.CONTROL_STEP.length){
						sendEndBatchNotification();
					}
				}
*/			}
			//logger.info("END: "+arg1.getDeclaringClass()+" "+arg1.getName()+" "+System.currentTimeMillis());		
		}
		
		public void afterThrowing(Method m, Object[] args, Object target, Throwable ex) 
		{ 
			if(m!=null && m.getName().equals("startBatch"))
			{
/*				int processId=LolaUtil.getProcessIdByClassName(m.getClass().getName());
				String processName=LolaUtil.getProcessNameByClassName(m.getClass().getName());
				logger.info("processId>>"+processId+">>processName"+processName);
				  if(processId!=-1 && processName !=null){
					  this.sendEmail("ERROR THROWN BY STEP:"+processId+ "("+processName+")", processName+" threw exception. Please check logs "+LolaUtil.getStackTrace(ex),
							  LolaProperites.getProperty(Constants.LOLA_EMAIL_ADDRESSES));
				  }
*/			}
			//logger.info("EXCEPTION: "+ex.getStackTrace().toString()+" "+m.getDeclaringClass()+" "+m.getName()+" "+System.currentTimeMillis());	
		}
		
		private void sendEmail(String mailSubject, String mailBody,String emailAddresses)
		{
			try {
				//LolaUtil.sendLOLAMail(mailSubject, mailBody,emailAddresses);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("Error occurred while sending email",e);
			}
			
		}
		
		/**
		 * Notifies users about batch start
		 */
		private void sendStartBatchNotification()
		{
			  //String sendEmailToUsers=LolaProperites.getProperty(Constants.LOLA_SEND_EMAIL_TO_USERS);
			  //logger.info("LOLA_SEND_EMAIL_TO_USERS:="+sendEmailToUsers);
			  //if(sendEmailToUsers!=null && sendEmailToUsers.equals("1")){
				//  String batchAsOfDate="N/A";
				  /*LolaContextBVO contextBVO = lolaContextService.getCurrBatchRunContext();
				  if(contextBVO !=null && contextBVO.getBatchAsofDate()!=null){
				  	batchAsOfDate=LolaUtil.getDateAsString(contextBVO.getBatchAsofDate());
				  }
				  
				  String batchStartTime="N/A";
				  Date batchStartDate = lolaBatchService.getBatchStartTime();
				  if(batchStartDate !=null){
					  batchStartTime=batchStartDate.toString();
				  }
				  
				  
				  this.sendEmail("LOLA Monthly Batch - Started",
						  "Monthly batch process for sourcing data started on "+batchStartTime+".  The LOLA application cannot be accessed " +
						  "at this time.  LOLA reporting data in CRRT for Batch As of Date ("+batchAsOfDate+") should not be used " +
						  "until batch is completed.",
						  LolaProperites.getProperty(Constants.LOLA_EMAIL_USER_ADDRESSES));*/
			  //}
		  
		}
		
		/**
		 * Notifies users about batch completion
		 */
		private void sendEndBatchNotification()
		{
			  /*String sendEmailToUsers=LolaProperites.getProperty(Constants.LOLA_SEND_EMAIL_TO_USERS);
			  logger.info("LOLA_SEND_EMAIL_TO_USERS:="+sendEmailToUsers);
			  if(sendEmailToUsers!=null && sendEmailToUsers.equals("1")){
				  String batchAsOfDate="N/A";
				  LolaContextBVO contextBVO = lolaContextService.getCurrBatchRunContext();
				  if(contextBVO !=null && contextBVO.getBatchAsofDate()!=null){
				  	batchAsOfDate=LolaUtil.getDateAsString(contextBVO.getBatchAsofDate());
				  }
				  
				  this.sendEmail("LOLA Monthly Batch - Completed",
						  "The LOLA Monthly batch process for Batch As of Date ("+batchAsOfDate+") has completed.  " +
						  "LOLA Application and LOLA reporting data in CRRT have been updated with latest batch and is now available for use.",
						  LolaProperites.getProperty(Constants.LOLA_EMAIL_USER_ADDRESSES));
			  }*/
		  
		}
	/*	
		public LolaContextService getLolaContextService() {
			return lolaContextService;
		}
		public void setLolaContextService(LolaContextService lolaContextService) {
			this.lolaContextService = lolaContextService;
		}
		public LolaBatchService getLolaBatchService() {
			return lolaBatchService;
		}
		public void setLolaBatchService(LolaBatchService lolaBatchService) {
			this.lolaBatchService = lolaBatchService;
		}*/

}
